﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
using OBUActivation;

namespace OBUActivation.Comm
{
   public class BlePortData : PortData
    {
        private Form1 mForm;
        /// <summary>
        /// 连接的蓝牙数目
        /// </summary>
        public static byte bleConnCount;

        public BlePortData(Form1 form, string mPortName, int mBandRate) :
            base(mPortName, mBandRate)
        {
            mForm = form;
        }

        public void SendBleRawByteArrayData(byte[] sendMsg)
        {
            if (sendMsg == null)
                throw new NullReferenceException("发送数据字节数组为null");
            SendData(sendMsg);
        }

        /// <summary>
        /// 搜索Ble设备
        /// </summary>
        public void ATScanBleDevice()
        {
            // 开启扫描，返回对应的设备名称AT+SCAN
            //byte[] msg = BleATComm.PackageATData("AT+SCAN\r\n");
            SendData("AT+SCAN\r\n");
            mForm.AppendInfoText("发送SCAN的AT命令");
        }

        /// <summary>
        /// 连接对应的蓝牙设备，一主多从
        /// </summary>
        /// <param name="p"></param>
        public void ATConnectDevices()
        {
            // 发送AT命令连接对应蓝牙设备
           //byte[] msg = BleATComm.PackageATData("AT+CONN\r\n");
            SendData("AT+CONN\r\n");
            mForm.AppendInfoText("发送CONN的AT命令");
        }

        /// <summary>
        /// 发送AT命令重置设备
        /// </summary>
        public void ATResetDevices()
        {
            // 发送AT命令连接对应蓝牙设备
           // byte[] msg = BleATComm.PackageATData("AT+RESET\r\n");
            //SendData("AT+RESET" + System.Environment.NewLine); 
            SendData("AT+RESET\r\n");
            mForm.AppendInfoText("发送RESET的AT命令");
            isConn = false;
            isScanSuccess = false;
        }
        
        string[] mScanAddrs = null;
        string[] mConnAddrs = null;
        bool isConn = false;
        bool isScanSuccess = false;
        bool isReceived = false;
        public string test="";
        public bool IsConn
        {
            get { return isConn; }
            set { }
        }

        public bool IsScanSuccess
        {
            get { return isScanSuccess; }
            set { }
        }

        public bool IsReceived
        {
            get { return isReceived; }
            set { isReceived = value; }
        }

        /// <summary>
        /// 解析出是AT命令还是透传命令
        /// </summary>
        /// <param name="raw">去掉了报文头和报文尾的元数据！</param>
        /// <returns>类型：1-AT命令， 2-透传命令</returns>
        public byte isAtOrTransfer(byte[] raw)
        {
            // 默认是AT命令
            byte type = 0x01;
            // 解析
            string rawStr = System.Text.Encoding.Default.GetString(raw);
            if (rawStr.Substring(0, 2) == "OK") type = 0x01;
            else if (rawStr.Contains("OK")) type = 0x01;
            else type = 0x02;
            return type;
        }

      
    }
}
